import { loadJs } from '../src/utils'
import EventEmit from '../src/event/eventEmit'
import { initCode } from './config'

// 默认配置
const defaultOption = {
  language: 'html',
  theme: 'vs-dark',
  path: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.14.3/min/vs/',
  jsUrl: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.14.3/min/vs/loader.js',
  moduleName: 'vs/editor/editor.main',
  // 初始化代码
  content: initCode,
}
/**
 * @description 基于monaco编辑器的二次封装
 * @constructor Editor
 */
export default class Editor extends EventEmit {
  constructor(config = {}) {
    super()
    this.editor = null
    this.initCode = null
    this._init(config)
  }
  /**
   * @description 初始化
   * @param {object} config 配置项
   */
  _init (config) {
    const configData = { ...defaultOption, ...config }
    const { id, content, language, theme, jsUrl, path, moduleName } = configData
    loadJs(jsUrl).then(() => {
      // 配置路径和加载模块
      require.config({
        paths: { vs: path },
        // 中文版本
        'vs/nls': { availableLanguages: { '*': 'zh-cn' } },
      })
      const that = this
      require([moduleName], function () {
        const monaco = window.monaco
        const model = monaco.editor.createModel(content, language)
        const dom = document.getElementById(id)
        that.editor = monaco.editor.create(dom, {
          model,
          //主题:vs、vs-dark、hc-black
          theme,
          //自适应调整
          automaticLayout: true,
          //代码略缩图
          minimap: { enabled: false },
          // 是否显示菜单
          contextmenu: false,
        })
        that.initCode = content
        // 编辑器对象加载完成触发事件
        that.trigger('load', { model, editor: that.editor })
      })
    })
  }

  /**
   * @description 自定义事事件回调
   * @param {String} type 事件类型
   * @param {Function} callback 回调函数
   */
  on (type, callback) {
    if (typeof callback !== 'function') return
    this.listen(type, callback)
  }

  /**
   * @description 获取值
   */
  getValue () {
    return this.editor.getValue()
  }

  /**
   * @description 设置值
   */
  setValue (content) {
    this.editor.setValue(content)
  }
}
